package com.ltxtiyu.video.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.ltxtiyu.video.bean.MessageInfoBean;
import com.ltxtiyu.video.bean.VideoInfoBean;
import com.ltxtiyu.video.cacheDao.ConfigCacheDao;
import com.ltxtiyu.video.cacheDao.MomentCacheDao;
import com.ltxtiyu.video.cacheDao.UserCacheDao;
import com.ltxtiyu.video.cacheDao.VideoCacheDao;
import com.ltxtiyu.video.common.CodeTypeConstant;
import com.ltxtiyu.video.common.ConfigConstant;
import com.ltxtiyu.video.common.JsonTool;
import com.ltxtiyu.video.common.RetEnum;
import com.ltxtiyu.video.dao.ltx.*;
import com.ltxtiyu.video.entity.*;
import com.ltxtiyu.video.service.app.MessageService;
import com.ltxtiyu.video.tool.AliTool;
import com.ltxtiyu.video.tool.ObjectTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.*;

@Service
public class MessageServiceImpl implements MessageService {
    public static final Logger LOGGER = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Autowired
    StringRedisTemplate stringRedisTemplate;    // redis
    @Autowired
    AmqpTemplate amqpTemplate;  // rabbitMq


    @Autowired
    MessageDao messageDao;
    @Autowired
    ConfigCacheDao configCacheDao;
    @Autowired
    VideoCacheDao videoCacheDao;
    @Autowired
    UserFollowDao userFollowDao;
    @Autowired
    CommentDao commentDao;
    @Autowired
    MomentCacheDao momentCacheDao;
    @Autowired
    MomentCountDao momentCountDao;
    @Autowired
    MomentLikeDao momentLikeDao;
    @Autowired
    UserCacheDao userCacheDao;
    @Autowired
    AreaDao areaDao;

    /**
     * 消息首页
     * @param params
     * @return
     */
    @Override
    public String index(Map<String, String> params) {
        Integer start = Integer.parseInt(params.get("start"));
        Integer rows = Integer.parseInt(params.get("rows"));
        Integer userId = Integer.parseInt(params.get("userId"));
        Date likeTipsCreateTime = new Date();
        Date followCreateTime = new Date();
        String followTipsNickname = "";
        String likeTipsNickname = "";

        // 查询未读点赞消息数量
        Map<Object, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("type", CodeTypeConstant.MESSAGE_CONTENT_TYPE_122);     // 点赞
        List<Message> likeMessageList = messageDao.selectUnreadCountByParams(map);
        Integer likeTipsCount = likeMessageList.size();
        if(likeMessageList.size() > 0){
            Message message = likeMessageList.get(0);   // 只需要最新的那个消息
            if(message != null && StringUtils.isNotBlank(message.getCotnent())){
                likeTipsCreateTime = message.getCreateTime();   // 最新消息时间
                try{    // 获取第一个消息内容里存的昵称
                    MessageInfoBean messageInfoBean = JSON.parseObject(message.getCotnent(), MessageInfoBean.class);
                    String nickName = messageInfoBean.getSenderNickName();
                    if(StringUtils.isNotBlank(nickName)){
                        likeTipsNickname = nickName;
                    }
                }catch (Exception e){
                    LOGGER.info(">>>>>>>>>>>>>解析消息内容出错 messgeId: {}, 错误信息:{}",message.getId(),e);
                }
            }
        }
        map.clear();
        // 获取新增粉丝未读消息数量
        map.put("userId",userId);
        map.put("type", CodeTypeConstant.MESSAGE_CONTENT_TYPE_123);     // 粉丝
        List<Message> followMessageList = messageDao.selectUnreadCountByParams(map);
        Integer followTipsCount = followMessageList.size();
        if(followMessageList.size() > 0){
            Message message = followMessageList.get(0);
            if(message != null && StringUtils.isNotBlank(message.getCotnent())){
                followCreateTime = message.getCreateTime();     // 最新动态的时间
                try{    // 获取第一个消息内容里存的昵称
                    MessageInfoBean messageInfoBean = JSON.parseObject(message.getCotnent(), MessageInfoBean.class);
                    String nickName = messageInfoBean.getSenderNickName();
                    if(StringUtils.isNotBlank(nickName)){
                        followTipsNickname = nickName;
                    }
                }catch (Exception e){
                    LOGGER.info(">>>>>>>>>>>>>解析消息内容出错 messgeId: {}, 错误信息:{}",message.getId(),e);
                }
            }
        }


        map.clear();
        map.put("userId",userId);
        List<Integer> types = new ArrayList<>();
        types.add(CodeTypeConstant.MESSAGE_CONTENT_TYPE_120);   // 评论
        types.add(CodeTypeConstant.MESSAGE_CONTENT_TYPE_121);   // @
        map.put("types",types);
        map.put("start",start);
        map.put("rows",rows);
        List<Message> messages = messageDao.selectListByParams(map);
        List<Map<String,Object>> messageList = new ArrayList<>();

        // 获取图片alitool
        String OSS_CDN = configCacheDao.selectByCkey(ConfigConstant.OSS_CDN).getCvalue();
        String ACCESS_ID = configCacheDao.selectByCkey(ConfigConstant.ACCESS_ID).getCvalue();
        String ACCESS_KEY = configCacheDao.selectByCkey(ConfigConstant.ACCESS_KEY).getCvalue();
        String BUCKET_ID = configCacheDao.selectByCkey(ConfigConstant.BUCKET_ID).getCvalue();
        // 查看图片用OSS_CDN
        AliTool aliTool = AliTool.getInstance(OSS_CDN, ACCESS_ID, ACCESS_KEY, BUCKET_ID);
        // 获取redis刷新数据到数据库的时间配置
        Integer refreshWriteTime = Integer.parseInt(configCacheDao.selectByCkey(ConfigConstant.REFRESH_WRITE_TIME).getCvalue().trim());
        for(Message msg:messages){
            // 获取消息信息
            Map<String, Object> msgResult = getMessageInfo(userId,refreshWriteTime,msg, aliTool);
            // 将@和评论的消息都设置为已读
            msg.setIsRead(1);
            messageDao.updateByPrimaryKeySelective(msg);
            messageList.add(msgResult);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("messageList",messageList);
        result.put("likeTipsCount",likeTipsCount);
        result.put("likeTipsNickname",likeTipsNickname);
        result.put("followTipsCount",followTipsCount);
        result.put("followTipsNickname",followTipsNickname);
        result.put("likeTipsCreateTime",likeTipsCreateTime);
        result.put("followCreateTime",followCreateTime);
        return JsonTool.genJson(RetEnum.SUCCESS,result);
    }

    /**
     * 消息列表
     * @param params
     * @return
     */
    @Override
    public String listMessage(Map<String, String> params) {
        Integer start = Integer.parseInt(params.get("start"));
        Integer rows = Integer.parseInt(params.get("rows"));
        Integer userId = Integer.parseInt(params.get("userId"));
        Integer viewType = ObjectTool.numberOrNull(params.get("viewType")); // vierTyoe即最后查询type
        if(viewType == null || (!viewType.equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_122)
                    && !viewType.equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_123))){    // 点赞 和 粉丝
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);   // 请求参数错误
        }

        // 查询未读点赞消息数量
        Map<Object, Object> map = new HashMap<>();
        map.put("userId",userId);
        List<Integer> types = new ArrayList<>();
        types.add(viewType);   // 点赞 或 粉丝
        map.put("types",types);
        map.put("start",start);
        map.put("rows",rows);
        List<Message> messages = messageDao.selectListByParams(map);
        List<Map<String,Object>> messageList = new ArrayList<>();

        // 获取图片alitool
        String OSS_CDN = configCacheDao.selectByCkey(ConfigConstant.OSS_CDN).getCvalue();
        String ACCESS_ID = configCacheDao.selectByCkey(ConfigConstant.ACCESS_ID).getCvalue();
        String ACCESS_KEY = configCacheDao.selectByCkey(ConfigConstant.ACCESS_KEY).getCvalue();
        String BUCKET_ID = configCacheDao.selectByCkey(ConfigConstant.BUCKET_ID).getCvalue();
        // 查看图片用OSS_CDN
        AliTool aliTool = AliTool.getInstance(OSS_CDN, ACCESS_ID, ACCESS_KEY, BUCKET_ID);
        // 获取redis刷新数据到数据库的时间配置
        Integer refreshWriteTime = Integer.parseInt(configCacheDao.selectByCkey(ConfigConstant.REFRESH_WRITE_TIME).getCvalue().trim());
        for(Message msg:messages){
            // 获取消息信息
            Map<String, Object> msgResult = getMessageInfo(userId, refreshWriteTime, msg, aliTool);
            messageList.add(msgResult);
        }
        /*Map<String, Object> readMap = new HashMap<>();
        readMap.put("type",viewType);
        readMap.put("userId",userId);
        // 设置消息为已读
        messageDao.readMessageByParams(readMap);*/

        Map<String, Object> result = new HashMap<>();
        result.put("messageList",messageList);
        return JsonTool.genJson(RetEnum.SUCCESS,result);
    }

    /**
     * 已读消息
     * 暂时只是点赞和粉丝
     * "@" 和 评论进首页的时候就已读了
     * @param params
     * @return
     */
    @Override
    public String readMessage(Map<String, String> params) {
        Integer userId = Integer.parseInt(params.get("userId"));
        Integer viewType = ObjectTool.numberOrNull(params.get("viewType")); // vierType即最后查询type
        if(viewType == null || (!viewType.equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_122)
                && !viewType.equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_123))){    // 点赞 和 粉丝
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);   // 请求参数错误
        }
        Map<String, Object> map = new HashMap<>();
        map.put("type",viewType);
        map.put("userId",userId);
        // 设置消息为已读
        messageDao.readMessageByParams(map);
        return JsonTool.genJson(RetEnum.SUCCESS);
    }

    /**
     * 删除消息
     * 目前只有删除评论消息时会用到
     * 删除评论做逻辑删除
     * @param params
     * @return
     */
    @Override
    public String deleteMessage(Map<String, String> params) {
        Integer userId = Integer.parseInt(params.get("userId"));
        Integer type = ObjectTool.numberOrNull(params.get("type"));
        Integer msgId = ObjectTool.numberOrNull(params.get("msgId"));
        Integer commentId = ObjectTool.numberOrNull(params.get("commentId"));
        if(type == null || msgId == null || commentId == null || !type.equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_120)){
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        // 删除消息
        messageDao.deleteByPrimaryKey(msgId);
        if(type.equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_120)){  // 评论类消息
            // 逻辑删除评论
            Comment comment = commentDao.selectByPrimaryKey(commentId);
            if(comment == null && comment.getStatus().intValue() == 0){
                return JsonTool.genJson(RetEnum.MOMENT_COMMENT_DELETED);    // 已经被删除
            }
            Moment moment = momentCacheDao.selectByPrimaryKey(comment.getMomentId());
            if(moment != null && moment.getPublisher().equals(userId)){ // 发布者是当前登录用户
                if(comment.getStatus().intValue() != 0){
                    comment.setStatus(0);
                    commentDao.updateByPrimaryKeySelective(comment);
                }
            }

            // redis缓存里评论数量-1
            Integer momentId = comment.getMomentId();
            try{
                String momentJson = (String) stringRedisTemplate.opsForHash().get(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, momentId + "");
                if(StringUtils.isNotBlank(momentJson)){
                    Map<String, String> redisMomentMap = (Map<String, String>) JSON.parse(momentJson);
                    Integer commentCount = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT_NOW));
                    Integer finalCommentCount = new Integer(commentCount.intValue() - 1);
                    if(finalCommentCount.intValue() < 0){
                        finalCommentCount = 0;          // 防止出现负数
                    }
                    redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT_NOW,finalCommentCount+"");
                    stringRedisTemplate.opsForHash().put(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, momentId + "", JSON.toJSONString(redisMomentMap));
                }
            }catch (Exception e){
                LOGGER.info(">>>>>>>>>>>>>>>>>>修改redis评论数失败,momentId:{}",momentId);
            }
        }
        return JsonTool.genJson(RetEnum.SUCCESS);
    }

    /**
     * 获取消息信息
     * @param msg
     * @return
     */
    private Map<String, Object> getMessageInfo(Integer realUserId, Integer refreshWriteTime, Message msg, AliTool aliTool) {
        Map<String, Object> msgResult = new HashMap<>();
        Integer senderId = 0;
        String senderNickName = "";
        String senderHeadPortraitUrl = "";
        String messageBody = "";
        Integer beOperateObjectId = 0;
        String videoCover = "";
        Integer commentId = 0;
        Integer isRead = 0;
        Date createTime = new Date();
        Integer isFollow = 0;
        String textExtra= "";
        Map<String, Object> momentMap = new HashMap<>();
        if(msg != null && StringUtils.isNotBlank(msg.getCotnent())){
            try{    // 获取第一个消息内容里存的昵称
                MessageInfoBean bean = JSON.parseObject(msg.getCotnent(), MessageInfoBean.class);
                senderId = bean.getSenderId();
                senderNickName = bean.getSenderNickName();
                if(StringUtils.isNotBlank(bean.getSenderHeadPortraitId())){
                    senderHeadPortraitUrl = aliTool.getAccessURL(bean.getSenderHeadPortraitId());
                }
                messageBody = bean.getMessageBody();
                beOperateObjectId = bean.getBeOperateObjectId();   // 评论 和 @ 的被操作对象都是动态
                if(bean.getVideoId() != null){   // 获取视频封面
                    Video video = videoCacheDao.selectByPrimaryKey(bean.getVideoId());
                    if(video != null){
                        try {
                            if(StringUtils.isNotBlank(video.getVideoInfo())){
                                VideoInfoBean videoInfoBean = JSON.parseObject(video.getVideoInfo(), VideoInfoBean.class);
                                videoCover = videoInfoBean.getCoverUrl();
                            }
                        }catch (Exception e){
                            LOGGER.info(">>>>>>>>>>>>>解析获取视频json出错, videoId: {}, 错误信息: {}",video.getId(),e);
                        }
                    }
                }
                // 评论或@你需要动态信息,app初始化数据
                if(msg.getType().equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_120)
                        || msg.getType().equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_121)){
                    commentId = bean.getCommentId();
                    if(StringUtils.isNotBlank(bean.getTextExtra())){
                        textExtra = bean.getTextExtra();
                    }
                    if(bean.getMomentId() != null){
                        Moment moment = momentCacheDao.selectByPrimaryKey(bean.getMomentId());
                        if(moment != null){
                            momentMap = this.getMomentVideoInfoMap(realUserId, refreshWriteTime, moment);
                            String nickName = "";
                            String provinceName = "";
                            String cityName = "";
                            String tempHeadPortraitUrl = "";
                            Integer tempIsFollow = 0;
                            if(realUserId > 0){     // 用户有登陆, 查询关注关系
                                if(realUserId.equals(moment.getPermissionType())){  // 是自己发布的
                                    isFollow = -1;  // 自己发布的,没有+ √
                                }else {
                                    // 查询是否关注
                                    Map<String, Object> tempMap = new HashMap<>();
                                    tempMap.put("userId",moment.getPublisher());
                                    tempMap.put("followerId",realUserId);
                                    List<UserFollow> userFollows = userFollowDao.selectHasFollow(tempMap);
                                    if(userFollows.size() > 0){ // 有关注关系
                                        tempIsFollow = 1;
                                    }
                                }
                            }
                            if(moment != null && moment.getPublisher() != null){
                                User user = userCacheDao.selectByPrimaryKey(moment.getPublisher());
                                if(user.getResidenceProvince() != null){    // 获取省市名称
                                    provinceName = areaDao.selectByPrimaryKey(user.getResidenceProvince()).getName();
                                }
                                if(user.getResidenceCity() != null){
                                    cityName = areaDao.selectByPrimaryKey(user.getResidenceCity()).getName();
                                }
                                if(StringUtils.isNotBlank(user.getHeadPortraitId())){   // 获取头像地址
                                    tempHeadPortraitUrl = aliTool.getAccessURL(user.getHeadPortraitId());
                                }
                                nickName = user.getNickName();
                            }
                            /* 发布人信息 */
                            momentMap.put("publisher",moment.getPublisher());
                            momentMap.put("nickName",nickName);
                            momentMap.put("provinceName",provinceName);
                            momentMap.put("cityName",cityName);
                            momentMap.put("headPortraitUrl",tempHeadPortraitUrl);
                            momentMap.put("isFollow",tempIsFollow);
                        }
                    }
                }
                if(msg.getType().equals(CodeTypeConstant.MESSAGE_CONTENT_TYPE_123)){    //  粉丝

                    // 查询是否关注
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId",senderId);     // 注意关注对象关系
                    map.put("followerId",beOperateObjectId);   // 这里被操作对象是自己
                    List<UserFollow> userFollows = userFollowDao.selectHasFollow(map);
                    if(userFollows.size() > 0){ // 有关注关系
                        isFollow = 1;
                    }

                }
                isRead = msg.getIsRead();
                createTime = msg.getCreateTime();
            }catch (Exception e){
                LOGGER.info(">>>>>>>>>>>>>解析消息内容出错 messgeId: {}, 错误信息:{}",msg.getId(),e);
            }
        }
        msgResult.put("msgId",msg.getId());
        msgResult.put("type",msg.getType());
        msgResult.put("senderId",senderId);
        msgResult.put("senderHeadPortraitUrl",senderHeadPortraitUrl);
        msgResult.put("senderNickName",senderNickName);
        msgResult.put("messageBody",messageBody);
        msgResult.put("beOperateObjectId",beOperateObjectId);
        msgResult.put("videoCover",videoCover);
        msgResult.put("commentId",commentId);
        msgResult.put("isRead",isRead);
        msgResult.put("createTime",createTime);
        msgResult.put("isFollow",isFollow);
        msgResult.put("textExtra",textExtra);
        msgResult.put("moment",momentMap);
        return msgResult;
    }

    /**
     * 获取动态视频信息
     * @param realUserId
     * @param refreshWriteTime
     * @param moment
     * @return
     */
    private Map<String, Object> getMomentVideoInfoMap(Integer realUserId, Integer refreshWriteTime, Moment moment) {
        Map<String, Object> resultMoment = new HashMap<>();
        Integer likeCount = 0;
        Integer viewCount = 0;
        Integer shareCount = 0;
        Integer commentCount = 0;
        try{
            // 从redis中获取视频统计信息
            String momentJson = (String) stringRedisTemplate.opsForHash().get(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, moment.getId() + "");
            if(StringUtils.isBlank(momentJson)){    // redis中没有该动态信息, 存入
                MomentCount momentCount = momentCountDao.selectByMomentId(moment.getId());
                if(momentCount == null){
                    MomentCount tempMomentCount = new MomentCount();
                    tempMomentCount.setCountComment(0);
                    tempMomentCount.setCountLike(0);
                    tempMomentCount.setCountShare(0);
                    tempMomentCount.setCountView(0);
                    tempMomentCount.setMomentId(moment.getId());
                    tempMomentCount.setPublisher(moment.getPublisher());
                    tempMomentCount.setCreateTime(new Date());
                    momentCountDao.insertSelective(tempMomentCount);
                    momentCount = tempMomentCount;
                }
                // 存入redis
                Map<String, String> redisMomentMap = new HashMap<>();
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_MOMENT,momentCount.getMomentId()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_LIKE,momentCount.getCountLike()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW,momentCount.getCountView()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_SHARE,momentCount.getCountShare()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT,momentCount.getCountComment()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_LIKE_NOW,momentCount.getCountLike()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW_NOW,momentCount.getCountView()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_SHARE_NOW,momentCount.getCountShare()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT_NOW,momentCount.getCountComment()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_WRITE_TIME,new Date().getTime()+"");
                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_FLAG,1+"");
                stringRedisTemplate.opsForHash().put(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, moment.getId() + "", JSON.toJSONString(redisMomentMap));
            }else {
                Map<String, String> redisMomentMap = (Map<String, String>) JSON.parse(momentJson);
                likeCount = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_LIKE_NOW));
                viewCount = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW_NOW));
                shareCount = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_SHARE_NOW));
                commentCount = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT_NOW));

                Integer likeCountOld = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_LIKE));
                Integer viewCountOld = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW));
                Integer shareCountOld = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_SHARE));
                Integer commentCountOld = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_COMMENT));
                Integer isFinish = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_FLAG));
                Long writeTime = Long.parseLong(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_WRITE_TIME));
                long nowTime = new Date().getTime();    // 超过刷新时间才执行
                if(isFinish.intValue() == 1 && ((nowTime - writeTime.longValue()) >= refreshWriteTime)){   // 0:队列存在,等待执行 1:可以发送新的队列
                    if(!likeCount.equals(likeCountOld) || !viewCount.equals(viewCountOld)
                            || !shareCount.equals(shareCountOld) || !commentCount.equals(commentCountOld)){
                        // 数据发生变化,发送队列消息,将新数据写入数据库
                        // 先修改状态位
                        redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_FLAG,0+"");  // 处理中
                        stringRedisTemplate.opsForHash().put(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, moment.getId() + "", JSON.toJSONString(redisMomentMap));

                        // 修改写入时间
                        redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_WRITE_TIME,new Date().getTime()+"");
                        amqpTemplate.convertAndSend(ConfigConstant.MESSAGE_NAME_MOMENT_REFRESH_WRITE,redisMomentMap);
                        LOGGER.info(">>>>>>>>>>>>MomentRefreshWriteMessage发出消息, 参数:{}",redisMomentMap.toString());
                    }

                }
            }
        }catch (Exception e){
            LOGGER.error(">>>>>>>>>>>>>>从redis中获取视频信息发生错误, momentId {},错误信息  {}",moment.getId(),e);
        }
        // 获取视频信息
        Integer videoId = moment.getVideoId();
        Video video = videoCacheDao.selectByPrimaryKey(videoId);
        String playUrl = "";
        String coverUrl = "";
        String duration = "0";
        try{
            if(video != null){
                String videoInfo = video.getVideoInfo();
                if(video.getStatus().intValue() == 1 && StringUtils.isNotBlank(videoInfo)){  // 有视频信息缓存
                    VideoInfoBean videoInfoBean = JSON.parseObject(videoInfo, VideoInfoBean.class);
                    playUrl = videoInfoBean.getPlayUrl();
                    coverUrl = videoInfoBean.getCoverUrl();
                    duration = videoInfoBean.getDuration();
                }
            }
        }catch (Exception e){
            LOGGER.error(">>>>>>>>>>>>>>发生错误:获取视频信息  {}",e);
        }
        // 查询该用户是否对视频点赞过
        Integer hasLiked = 0;
        if(realUserId.intValue() > 0){  // 用户未登录时id为-1
            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("userId",realUserId);
            tempMap.put("momentId",moment.getId());
            List<MomentLike> momentLikeList = momentLikeDao.selectMomentHasLiked(tempMap);
            if(momentLikeList.size() > 0){   // 点过赞
                hasLiked = 1;
            }
        }
        /* 动态社交信息 */
        resultMoment.put("viewCount",viewCount);
        resultMoment.put("likeCount",likeCount);
        resultMoment.put("shareCount",shareCount);
        resultMoment.put("commentCount",commentCount);
        resultMoment.put("hasLiked",hasLiked);
        /* 动态视频信息 */
        resultMoment.put("playUrl",playUrl);
        resultMoment.put("coverUrl",coverUrl);
        resultMoment.put("duration",duration);
        /* 动态信息 */
        resultMoment.put("momentId",moment.getId());
        resultMoment.put("contentText",moment.getContentText());
        resultMoment.put("textExtra",moment.getTextExtra());
        resultMoment.put("permissionType",moment.getPermissionType());
        return resultMoment;
    }
}
